import { Codewin } from './generated/Codewin'
import type { RoleVo, RoleAddRequest } from './generated/data-contracts'
import { message } from 'ant-design-vue'
import { useAuthStore } from '@/stores'

// 获取token的辅助函数
const getAuthToken = (): string | null => {
  const authStore = useAuthStore()
  return authStore.token
}

// 创建带认证头的API配置
const createAuthHeaders = () => {
  const token = getAuthToken()
  return token ? { Authorization: `Bearer ${token}` } : {}
}

// 扩展角色类型，添加前端展示需要的字段
export interface ExtendedRole extends RoleVo {
  id: string
  roleName: string
  prompt: string
  // 后端API字段
  voiceId?: string
  knowledgeId?: string
  // 前端展示用的扩展字段
  avatar?: string
  category?: string
  era?: string
  tags?: string[]
  status?: string // 角色状态：active/inactive
  isDefault?: boolean // 标识是否为默认角色
  createAt?: string // 兼容RoleCardList组件的createAt字段
}

// 角色列表查询参数
export interface RoleListParams {
  pageNo: number
  pageSize: number
  keyword?: string
  category?: string
  tags?: string[]
}

// 角色列表响应数据
export interface RoleListResponse {
  records: ExtendedRole[]
  total: number
  current: number
  size: number
}

class RoleService {
  private api: Codewin

  constructor() {
    this.api = new Codewin({
      headers: createAuthHeaders()
    })
  }

  /**
   * 获取角色列表
   */
  async getRoleList(params: RoleListParams): Promise<RoleListResponse> {
    try {
      const response = await this.api.request({
        path: '/codewin/role/list',
        method: 'GET',
        query: {
          pageNo: params.pageNo,
          pageSize: params.pageSize
        },
        secure: true
      })

      if (response.data?.code === 0 && response.data.data) {
        const pageData = response.data.data

        // 将后端数据转换为前端需要的格式
        let records = (pageData.list || []).map((role: RoleVo) => ({
          ...role,
          id: role.id || 0,
          roleName: role.roleName || '',
          prompt: role.prompt || '',
          // 添加前端展示需要的默认值
          category: 'custom',
          era: '现代',
          tags: ['自定义']
        }))

        // 前端过滤逻辑
        if (params.keyword && typeof params.keyword === 'string') {
          const keyword = params.keyword.toLowerCase()
          records = records.filter((role: ExtendedRole) =>
            (role.roleName || '').toLowerCase().includes(keyword) ||
            (role.prompt || '').toLowerCase().includes(keyword) ||
            (role.tags || []).some((tag: string) => tag.toLowerCase().includes(keyword))
          )
        }

        if (params.category) {
          records = records.filter((role: ExtendedRole) => role.category === params.category)
        }

        if (params.tags && params.tags.length > 0) {
          records = records.filter((role: ExtendedRole) =>
            params.tags!.every((tag: string) => (role.tags || []).includes(tag))
          )
        }

        return {
          records,
          total: pageData.total || 0,
          current: pageData.current || params.pageNo,
          size: pageData.size || params.pageSize
        }
      } else {
        throw new Error(response.data?.message || '获取角色列表失败')
      }
    } catch (error) {
      console.error('获取角色列表失败:', error)
      throw error
    }
  }

  /**
   * 创建角色
   */
  async createRole(roleData: RoleAddRequest): Promise<boolean> {
    try {
      const response = await this.api.listRolesOnUser(roleData, {
        headers: createAuthHeaders()
      })

      // 修正响应码判断逻辑
      if (response.data?.code === 0 ) {
        // 移除这里的成功消息，由调用方处理
        return true
      } else {
        const errorMessage = response.data?.message || '角色创建失败'
        message.error(errorMessage)
        throw new Error(errorMessage)
      }
    } catch (error) {
      console.error('创建角色失败:', error)

      // 处理网络错误或其他异常
      if (error instanceof Error) {
        // 如果错误消息已经显示过，不重复显示
        if (!error.message.includes('角色创建失败:')) {
          message.error(`创建角色失败: ${error.message}`)
        }
        throw error
      }

      message.error('网络错误，角色创建失败')
      throw new Error('创建角色失败，请检查网络连接')
    }
  }

  /**
   * 更新角色
   */
  async updateRole(id: string, roleData: RoleAddRequest): Promise<boolean> {
    try {
      const response = await this.api.updateRole(id, roleData, {
        headers: createAuthHeaders()
      })

      if ( response.data?.code === 0) {
        return true
      } else {
        const errorMessage = response.data?.message || '角色更新失败'
        throw new Error(errorMessage)
      }
    } catch (error) {
      console.error('更新角色失败:', error)
      if (error instanceof Error) {
        throw new Error(`更新角色失败: ${error.message}`)
      }
      throw new Error('更新角色失败，请检查网络连接')
    }
  }

  /**
   * 删除角色
   */
  async deleteRole(id: string): Promise<boolean> {
    try {
      const response = await this.api.deleteRole(id, {
        headers: createAuthHeaders()
      })

      if ( response.data?.code === 0) {
        return true
      } else {
        const errorMessage = response.data?.message || '角色删除失败'
        throw new Error(errorMessage)
      }
    } catch (error) {
      console.error('删除角色失败:', error)
      if (error instanceof Error) {
        throw new Error(`删除角色失败: ${error.message}`)
      }
      throw new Error('删除角色失败，请检查网络连接')
    }
  }

  /**
   * 获取默认角色列表
   */
  async getDefaultRoles(params: { pageNo: number; pageSize: number }): Promise<RoleListResponse> {
    try {
      const response = await this.api.request({
        path: '/codewin/role/list/default',
        method: 'GET',
        query: {
          pageNo: params.pageNo,
          pageSize: params.pageSize
        },
        secure: true
      })


      if (response.data?.code === 0 && response.data.data) {
        const pageData = response.data.data

        const records = (pageData.list || []).map((role: RoleVo) => ({
          ...role,
          id: role.id || 0,
          roleName: role.roleName || '',
          prompt: role.prompt || '',
          category: 'default',
          era: '经典',
          tags: ['默认', '推荐']
        }))

        return {
          records,
          total: pageData.total || 0,
          current: pageData.current || params.pageNo,
          size: pageData.size || params.pageSize
        }
      } else {
        throw new Error(response.data?.message || '获取默认角色列表失败')
      }
    } catch (error) {
      console.error('获取默认角色列表失败:', error)
      throw error
    }
  }
}

// 导出单例实例
export const roleService = new RoleService()
export default roleService
